package com.example.rouroudate.ui.history

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.example.rouroudate.R
import com.example.rouroudate.databinding.ActivityHistoryBinding
import com.example.rouroudate.ui.gallery.ui.DateSettingData
import com.example.rouroudate.ui.history.ui.HistoryItemView
import com.example.rouroudate.ui.home.ui.CircleDate
import com.example.rouroudate.ui.widget.BaseActivity
import com.example.rouroudate.ui.widget.DataEventBus
import com.example.rouroudate.ui.history.ui.HistoryMenuDialog
import com.example.rouroudate.util.*
import kotlinx.coroutines.launch

class HistoryActivity : BaseActivity() {

    private lateinit var binding: ActivityHistoryBinding

    private val width = DisplayUtils.getScreenWidth() / 2

    private var data = PrefManager.getStartDateArray(PrefManager.SortTypeDown)

    private lateinit var dateSettingData: DateSettingData

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityHistoryBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initData()
        initView()
    }

    private fun initData() {
        dateSettingData = if (data.size > 0) {
            val dateSize = data.sumOf {
                it.settingData.dateSize
            }.div(data.size)
            val hurtSize = data.sumOf {
                it.settingData.hurtSize
            }.div(data.size)
            DateSettingData(dateSize, hurtSize)
        } else {
            DateSettingData(0, 0)
        }
        binding.averageDateTv.text = String.format("%s天", dateSettingData.dateSize)
        binding.averageHurtTv.text = String.format("%s天", dateSettingData.hurtSize)
    }

    private fun initView() {
        binding.titleBar.apply {
            titleTv.setTextColor(ContextCompat.getColor(this@HistoryActivity, R.color.pink))
            titleTv.text = getString(R.string.all_history)
            leftView.background = AppCompatResources.getDrawable(
                this@HistoryActivity,
                R.drawable.ic_back
            )
            leftView.setOnClickListener {
                finish()
            }
        }
        binding.listView.adapter = object : BaseAdapter() {
            override fun getCount() = data.size

            override fun getItem(p0: Int) = data[p0]

            override fun getItemId(p0: Int) = p0.toLong()

            override fun getView(position: Int, p1: View?, p2: ViewGroup?): View {
                val view = if (position % 2 == 0) {
                    LayoutInflater.from(this@HistoryActivity)
                        .inflate(R.layout.history_list_view_item_one, null)
                } else {
                    LayoutInflater.from(this@HistoryActivity)
                        .inflate(R.layout.history_list_view_item_two, null)
                }
                val item = getItem(position)
                view.findViewById<HistoryItemView>(R.id.history_view).apply {
                    setDate(item)
                }
                view.findViewById<TextView>(R.id.date_tv).apply {
                    text = String.format("周期%s天", item.settingData.dateSize)
                }
                view.findViewById<TextView>(R.id.is_exception_tv).apply {
                    visibility = if (isExceptionData(item)) View.VISIBLE else View.GONE
                }
                view.findViewById<TextView>(R.id.hurt_tv).apply {
                    text = if (item.settingData.hurtSize < 10) {
                        String.format("经期 %s天", item.settingData.hurtSize)
                    } else {
                        String.format("经期%s天", item.settingData.hurtSize)
                    }
                }
                view.findViewById<ImageView>(R.id.edit_date_iv).setOnClickListener {
                    val dialog = HistoryMenuDialog(this@HistoryActivity).apply {
                        date = CircleDate(settingData = dateSettingData.copy())
                        setTitle(getString(R.string.delete_start_date))
                        setCallBack {
                            ToastUtils.show(
                                when (PrefManager.delStartDate(item)) {
                                    PrefManager.SUCCESS -> {
                                        data = PrefManager.getStartDateArray(PrefManager.SortTypeDown)
                                        lifecycleScope.launch {
                                            DataEventBus.deleteStartDate.emit(true)
                                        }
                                        notifyDataSetChanged()
                                        initData()
                                        getString(R.string.del_success)
                                    }
                                    PrefManager.FAIL -> {
                                        getString(R.string.del_fail)
                                    }
                                    else -> {
                                        ""
                                    }
                                }
                            )
                        }
                    }
                    dialog.show()
                }
                view.layoutParams =
                    LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, width)
                return view
            }
        }
    }

    private fun isExceptionData(item: CircleDate): Boolean {
        val maxDate = (dateSettingData.dateSize * 1.45f).toInt()
        val minDate = (dateSettingData.dateSize * 0.55f).toInt()
        val maxHurt = (dateSettingData.hurtSize * 1.45f).toInt()
        val minHurt = (dateSettingData.hurtSize * 0.55f).toInt()
        val date = item.settingData.dateSize
        val hurt = item.settingData.hurtSize
        return date >= maxDate || date <= minDate || date <= hurt || hurt >= maxHurt || hurt <= minHurt
    }
}